<template>
    <!--在套一层 是因为template模板只能往外暴露 一层 所以用一个div包裹-->
    <div>
        <home-header ></home-header>
        <home-swiper :list="swiperList"></home-swiper>
        <home-icons :list="iconsList"></home-icons>
        <home-recommend :list="recommendList"></home-recommend>
        <home-weekend :list="weekendList"></home-weekend>
    </div>
</template>

<script>
    // 引入的是一个局部组件
    // import HomeHeader from './components/header'
    // 引入轮播组件
    import HomeSwiper from './components/swiper'
    // 引入轮播组件
    import HomeIcons from './components/Icons'
    import HomeRecommend from './components/Recommend'
    import HomeWeekend from './components/weekend'
    // 要用axios发送ajax 必须引入
    import axios from "axios"
    // 引入 vuex
    import {mapState} from "vuex"
    export default {
        name: "home",
        components:{
            HomeHeader : () => import('./components/header'),
            HomeSwiper,
            HomeIcons,
            HomeRecommend,
            HomeWeekend
        },
        data () {
            return {
                lastcity:'',
                swiperList:[],
                iconsList:[],
                recommendList:[],
                weekendList:[]
            }
        },
        computed:{
            ...mapState(['city'])
        },
        methods:{
            // ajax
            getHomeInfo () {
                // axios返回一个promiss对象 所以可以用then
                // 逻辑优化 发送ajax的时候，应该带上city，city是vuex中存 的内容
                axios.get('/api/index.json?city='+this.city)
                    // then 是ajax后的执行，执行下 getHomeInfoSucc函数，打印下结果
                    .then(this.getHomeInfoSucc)
            },
            getHomeInfoSucc (res) {
                res=res.data
                // 如果后端返回的ret是true
                // 并且 res.data存在
                if(res.ret && res.data){
                    const data=res.data
                    this.swiperList=data.swiperList
                    this.iconsList=data.iconList
                    this.recommendList=data.recommendList
                    this.weekendList=data.weekendList
                }
                console.log(res)
            }
        },
        // 页面挂载之前
        mounted () {
            this.lastcity=this.city;
            console.log('mounted');
            // 执行下ajax
            this.getHomeInfo()
        },
        activated () {
            // 测试 keep-alive下多的一个生命周期函数
            // console.log('activated');
            if(this.lastcity!==this.city){
                this.lastcity=this.city
                this.getHomeInfo()
            }


        }
    }
</script>

<style scoped>

</style>